package com.jwdf.uda.ui.adapter;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.jwdf.uda.R;
import com.jwdf.uda.databinding.ItemPostImageBinding;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/6.
 */
public class PostImageAdapter extends AbsAdapter<String> {
    public static final int MAX_COUNT=9;
    public static final String TAG_ADD="add";
    public PostImageAdapter(Context context) {
        super(context);
        mData.add(TAG_ADD);
    }

    public void setData(List<String> items) {
        mData = new ArrayList<>(items);
        if (mData.size() < MAX_COUNT) {
            mData.add(TAG_ADD);
        }
        notifyDataSetChanged();
    }

    public void add(String item, int index) {
        mData.add(index, item);
        if (getCount() == MAX_COUNT + 1) {
            remove(TAG_ADD);
        }
        notifyDataSetChanged();
    }

    public void remove(String item) {
        mData.remove(item);
        if (getCount() < MAX_COUNT && !mData.contains(TAG_ADD)) {
            add(TAG_ADD, getCount());
        }
        notifyDataSetChanged();
    }

    public void remove(int position) {
        mData.remove(position);
        if (getCount() < MAX_COUNT && !mData.contains(TAG_ADD)) {
            add(TAG_ADD, getCount());
        }
        notifyDataSetChanged();
    }

    public int getRealCount() {
        return mData.contains(TAG_ADD) ? getCount() - 1 : getCount();
    }

    public ArrayList<String> getRealData() {
        ArrayList<String> images = new ArrayList<>(mData);
        images.remove(TAG_ADD);
        return images;
    }

    @Override
    protected AbsViewHolder onCreateViewHolder(ViewGroup parent, int itemType) {
        return new ImageViewHolder(mInflater.inflate(R.layout.item_post_image, parent, false));
    }

    private class ImageViewHolder extends AbsViewHolder<String> {
        private ItemPostImageBinding mBinding;

        public ImageViewHolder(View convertView) {
            super(convertView);
            mBinding = DataBindingUtil.bind(convertView);
        }

        @Override
        protected void onBindView(String path) {
            if (TextUtils.equals(path, TAG_ADD)) {
                mBinding.ivImage.setImageResource(R.mipmap.icon_add_image);
            } else {
                ImageLoader.getInstance().displayImage(path,mBinding.ivImage);
            }
        }
    }
}
